﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "checkwidget.h"

#include "serialportset.h"
#include <QTabWidget>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->tabWidget->clear();

    setWindowFlags(this->windowFlags() & ~Qt::WindowMaximizeButtonHint);
//    setFixedSize(width(),height());
    setFixedSize(1120,680);
    //添加Tab页面 ...
    m_pBatteryInfoWidget = new BatteryInfoWidget();
    ui->tabWidget->addTab(m_pBatteryInfoWidget,QString::fromLocal8Bit("电池信息"));
    ui->tabWidget->addTab(new ParameterSetupWidget(),QString::fromLocal8Bit("参数设置"));
    ui->tabWidget->addTab(new checkwidget(),QString::fromLocal8Bit("校准"));

    m_SerialPort = new SerialPort();
    connect(m_SerialPort,&SerialPort::SerialPortList,this,&MainWindow::GetUartPortList);
    connect(m_SerialPort,&SerialPort::RecvData,m_pBatteryInfoWidget,&BatteryInfoWidget::RecvData);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btn_start_clicked()
{
    QByteArray senddata;
    senddata.resize(5);

    senddata[0] = 0xAC;
    senddata[1] = 0xBD;
    senddata[2] = 0xB0;
    senddata[3] = 0x02;
    senddata[4] = 0;
    m_SerialPort->sendData(senddata,senddata.size());
}

void MainWindow::on_btn_configUart_clicked()
{
    m_SerialPort->scanSerial();
    serialportset setui;
    connect(&setui,&serialportset::selectPort,this,&MainWindow::selectPort);
    setui.setUartInfoList(m_UartInfoList);
    setui.show();
    setui.exec();
}

void  MainWindow::selectPort(int nUartIdx, int nPort)
{
    m_UartIdx = nUartIdx;
    m_PortNum = nPort;
}

void MainWindow::GetUartPortList(QList<QSerialPortInfo> serialList, int curIndex)
{
    m_UartInfoList = serialList;
}

void MainWindow::RecvData(QByteArray databuf, int datalen)
{


    m_pBatteryInfoWidget->setData(databuf,datalen);
}

void MainWindow::on_btn_openuart_clicked()
{
    if(m_SerialPort->isOpen())
    {
        m_SerialPort->closeUart();
        ui->btn_openuart->setText(QString::fromLocal8Bit("打开串口"));
    }
    else
    {
        bool ret = m_SerialPort->openUart(m_UartInfoList.at(m_UartIdx).portName(), m_PortNum);
        if(ret)
        {
            ui->btn_openuart->setText(QString::fromLocal8Bit("关闭串口"));
        }
        else
        {
            QMessageBox::warning(this,QString::fromLocal8Bit("警告"),QString::fromLocal8Bit("串口打开失败！"));
        }
    }
}
